package cn.com.homeyoda.aimate.aihealth.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.RequiresApi;
import androidx.camera.view.PreviewView;

public class CircularCameraContainer extends FrameLayout {
    private PreviewView previewView = null;
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Path path = new Path();

    public CircularCameraContainer(Context context) {
        this(context, null);
    }

    public CircularCameraContainer(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircularCameraContainer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            previewView = new PreviewView(context);
        }
        addView(previewView);

        setLayerType(LAYER_TYPE_SOFTWARE, null);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    public PreviewView getPreviewView() {
        return previewView;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        path.reset();
        float radius = Math.min(w, h) / 2f;
        path.addCircle(w / 2f, h / 2f, radius, Path.Direction.CW);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int saveCount = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null);
        }
        super.dispatchDraw(canvas);
        canvas.drawPath(path, paint);
        canvas.restoreToCount(saveCount);
    }
}
